<template>
  <div>
    <div class="top-bg" >
      <div class="item" v-if="userInfo.level<=2">
        <div class="first mr-10">用户姓名:</div>
        <el-input placeholder="请输入用户姓名" clearable maxlength="50" v-model="params.userName"></el-input>
      </div>
      <div class="item">
        <div class="first mr-10">查询日期:</div>
        <el-date-picker type="daterange" v-model="params.dateList" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期"
                        format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
      </div>
      <div class="item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetClick">重置</el-button>
        <el-button @click="exportClick" :disabled="!exportBtnEnable">导出</el-button>
      </div>
    </div>
    <div class="bg">
      <el-table :data="dataList"  stripe style="width: 100%;" border :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}">
        <el-table-column prop="userName" label="用户姓名" ></el-table-column>
        <el-table-column prop="dishName" label="所点菜品" ></el-table-column>
        <el-table-column prop="score" label="扣除金额" width="100"></el-table-column>
        <el-table-column prop="timeRange" label="档位名称">
          <template scope="scope">
            {{convertGearFromValue(scope.row.timeRange)}}
          </template>
        </el-table-column>
        <el-table-column prop="" label="应就餐时间">
          <template scope="scope">
            {{scope.row.targetDate+' 的 '+scope.row.gearTime}}
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="点餐时间"></el-table-column>
<!--        <el-table-column prop="targetDate" label="菜品生效日期" ></el-table-column>-->
<!--        <el-table-column prop="flagSend" label="是否赠送" width="100">-->
<!--          <template scope="scope">-->
<!--            <el-tag v-if="scope.row.flagSend===1" type="success">赠品</el-tag>-->
<!--            <el-tag v-else type="danger">非赠品</el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="pickUpCount" label="打包数量" width="100"></el-table-column>
        <el-table-column prop="orderCount" label="堂食数量" width="100">
          <template scope="scope">{{scope.row.orderCount - scope.row.pickUpCount}}</template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="flagSend" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" :disabled="canDeleteOrder(scope.row)" @click="deleteClick(scope.row)">取消点餐</el-button>
<!--            <el-button type="text" size="small" v-if="userInfo.level<3" @click="minusUserScoreClick(scope.row)">扣积分</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
                     :current-page="params.page" :page-sizes="[10, 20, 30, 50]" :page-size="params.pageSize"
                     :layout="params.total<10?'->,total':'->,total, sizes, prev, pager, next, jumper'" :total="params.total">
      </el-pagination>
      <el-dialog title="扣减金额" width="500px" v-if="showMinusScoreDialogFlag" :visible.sync="showMinusScoreDialogFlag" append-to-body :close-on-click-modal="false">
        <div class="flex-center mb-20">
          <div class="flex-center">
            <div class="mr-10 w-120 text-right">菜品名称</div>
            <div>{{currentChoseOrder.dishName||'-'}}</div>
          </div>
          <div class="flex-center" style="margin-left: 100px">
            <div class="mr-10 w-120 text-right">点菜人</div>
            <div>{{currentChoseOrder.userName||'-'}}</div>
          </div>
        </div>
        <div class="flex-center mb-20">
          <div class="mr-10 w-120 text-right">点餐时间</div>
          <div>{{currentChoseOrder.create_time||'-'}}</div>
        </div>
        <div class="flex-center mb-20">
          <div class="mr-10 w-120 text-right">扣除金额</div>
          <el-input type="number" oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}" class="mw300" v-model="currentRowMinusScore"></el-input>
        </div>
        <div class="flex-center-center">
          <el-button @click="cancelMinusClick">取消</el-button>
          <el-button type="primary" @click="certainMinusClick">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  ORDERING_GET_EXPORT_FROM_CHIEF,
  ORDERING_GET_GEARS_LIST,
  ORDERING_POST_POST_EXPORT_ORDER_DATA, ORDERING_POST_USER_ORDER_DELETE,
  ORDERING_POST_USER_ORDER_LIST, ORDERING_POST_USERS_SCORE_CHANGE
} from "@/assets/const/api";
import {exportExcel} from "js-utils/excel";
import {Validate} from "js-utils/validate";
import {getUserInfo} from "@/config/tools";

export default {
    name: '',
    mixins: [],
    components: {},
    props: {},
    data () {
        return {
          dataList:[],
          gearList:[],
          choseList:[],
          currentChoseOrder:{},
          timeRangeToMeal :{
            5: "早餐",
            6: "午餐",
            7: "晚餐",
            8: "夜宵"
          },
          timeRangeToMealAdmin :{
            5: "早餐合计",
            6: "午餐合计",
            7: "晚餐合计",
            8: "夜宵合计"
          },
          showMinusScoreDialogFlag:false,
          params:{
            userName:'',
            dateList:[],
            pageSize:10,
            page:1,
            total:0,
          },
          currentRowMinusScore:0,
        }
    },
    computed: {
      exportBtnEnable(){
        return !Validate.isEmpty(this.params.dateList);
      },
      canDeleteOrder:function(){
        return (row)=>{
          let arr = row.gearTime.split('-');
          if (!Validate.isEmpty(arr) && arr.length>1){
            let timeStr = row.targetDate + ' ' + arr[1] +':00';
            let today = new Date();
            const givenDate = new Date(timeStr);
            return today > givenDate;
          }
          return true;
        }
      },
      userInfo(){
        return this.$store.state.userInfo||{};
      }
    },
    watch: {},
    created() {
      this.resetData();
      getUserInfo();
      this.getGears();
      this.getData();
    },
    mounted () {},
    methods: {
      resetData(){
        this.params.userName = ''
        let todayDate = new Date();
        let sevenDaysAgo = new Date()
        sevenDaysAgo.setDate(todayDate.getDate() +14);
        let today = this.date2String(todayDate)
        let seven = this.date2String(sevenDaysAgo)
        this.params.dateList = [today,seven];
      },
      getData(){
        this.$http.get(ORDERING_POST_USER_ORDER_LIST,this.params).then(res=>{
          if(res.code === 200){
            this.dataList = res.data.data
            this.params.total = res.data.total
          }
        })
      },
      getGears(){
        this.$http.get(ORDERING_GET_GEARS_LIST).then(res=>{
          if(res.code === 200){
            this.gearList = res.data||[]
          }
        })
      },
      convertGearFromValue(val){
        let gear = this.gearList.find(v=>v.value === val)
        if (gear){
          return gear.name
        }
        return '-'
      },
      getOrderTimetext(row){
        let gear = this.gearList.find(v=>v.value === row.timeRange)
        if (gear){
          return gear.ableStartTime +'-' +gear.ableEndTime
        }
        return '-'
      },
      handleCurrentChange(val){
        this.params.page = val
        this.getData()
      },
      handleSizeChange(val){
        this.params.pageSize = val
        this.getData()
      },
      isCurrentTimeInRange(ableStartTime, ableEndTime) {
        const currentTime = new Date();
        // 获取当前时间的小时和分钟
        const currentHours = currentTime.getHours();
        const currentMinutes = currentTime.getMinutes();
        // 将当前时间转换为字符串格式，确保小时和分钟都是两位数
        const currentTimeStr = `${String(currentHours).padStart(2, '0')}:${String(currentMinutes).padStart(2, '0')}`;
        // 判断是否跨天
        if (ableStartTime > ableEndTime) {
          // 当前时间在跨天的情况下
          return currentTimeStr >= ableStartTime || currentTimeStr <= ableEndTime;
        } else {
          // 普通时间段
          return currentTimeStr >= ableStartTime && currentTimeStr <= ableEndTime;
        }
      },
      date2String(nowDate) {
        let year = nowDate.getFullYear()
        let month = nowDate.getMonth() + 1
        let day = nowDate.getDate()
        if (month < 10) month = '0' + month
        if (day < 10) day = '0' + day
        return year + '-' + month + '-' +day
      },
      handleSearch(){
        this.params.page = 1;
        this.getData()
      },
      resetClick(){
        this.resetData()
        this.getData()
      },
      // handleSelectionChange(val) {
      //   this.choseList = val;
      // },
      exportClick(){
        let dic = {...this.params};
        if (this.userInfo.level>2){
          dic['userName'] = this.userInfo.userName;
        }
        this.$http.post(ORDERING_POST_POST_EXPORT_ORDER_DATA,dic).then(res=>{
          let list = res.data ||[]
          let arr = [];
          list.forEach(e=>{
            let dic = {...e,week:this.getDayOfWeek(e.targetDate)};
            arr.push(dic);
          });
          let exportData = this.configExportData(arr);
          if (this.userInfo.level > 2){
            let header = {userName:'用户姓名',date:'日期',week:'星期',早餐:'早餐',午餐:'午餐',晚餐:'晚餐',夜宵:'夜宵',totalScore:'合计'}
            exportExcel(exportData, header, this.userInfo.userName+'用餐情况' , "xlsx");
          }else{
            //管理员
            let header = {userName:'用户姓名',date:'日期',week:'星期',
              早餐合计:'早餐',
              午餐:'午餐堂食',午餐打包:'午餐打包',午餐合计:'午餐合计',
              晚餐合计:'晚餐',
              totalScore:'合计'}
            exportExcel(exportData, header, '用餐情况' , "xlsx");
          }
        });
      },
      getDayOfWeek(dateString) {
        // 解析日期字符串，创建 Date 对象
        let date = new Date(dateString);
        // 获取星期几，0 表示星期日，6 表示星期六
        let daysOfWeek = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        let day = date.getDay();
        // 返回对应的星期
        return daysOfWeek[day];
      },
      configExportData(list){
        const result = {};
        list.forEach(item => {
          const { userName, targetDate, timeRange, week ,orderCount,pickUpCount} = item;
          let meal ;
          if (this.userInfo.level > 2){
            meal = this.timeRangeToMeal[timeRange] || "其他";
          }else{
            meal = this.timeRangeToMealAdmin[timeRange] || "其他";
          }
          if (!result[userName]) {
            result[userName] = {};
          }
          if (!result[userName][targetDate]) {
            if (this.userInfo.level > 2){
              result[userName][targetDate] = {
                userName: userName, date: targetDate,week:week, 早餐: null, 午餐: null, 晚餐: null, 夜宵: null, totalScore: 0
              };
            }else{
              result[userName][targetDate] = {
                userName: userName, date: targetDate,week:week, 早餐: null, 早餐打包:null,早餐合计:null, 午餐: null,午餐打包:null, 午餐合计:null, 晚餐: null, 晚餐打包:null,晚餐合计: null, 夜宵: null, totalScore: 0
              };
            }
          }
          result[userName][targetDate][meal] += orderCount || 0;
          if (this.userInfo.level<=2){
            let key2 = meal.slice(0,2);
            let keyPick = key2+'打包';
            result[userName][targetDate][key2] += (orderCount - pickUpCount);
            result[userName][targetDate][keyPick] += pickUpCount;

          }
        });

        // 将结果转成所需数组格式
        const finalResult = [];
        Object.values(result).forEach(userEntries => {
          Object.values(userEntries).forEach(entry => {
            if (this.userInfo.level > 2){
              entry.totalScore = entry.早餐 + entry.午餐 + entry.晚餐 + entry.夜宵;
            }else{
              entry.totalScore = entry.早餐合计 + entry.午餐合计 + entry.晚餐合计 + entry.夜宵;
            }
            let keys = Object.keys(entry);
            keys.forEach(k =>{
              if(Validate.isEmpty(entry[k])){
                entry[k] = '';
              }
            })
            finalResult.push(entry);
          });
        });
        finalResult.sort((a, b) => new Date(b.date) - new Date(a.date));

        return finalResult;
      },
      cancelMinusClick(){
        this.currentRowMinusScore = 0
        this.showMinusScoreDialogFlag=false
      },
      certainMinusClick(){
        if (Number(this.currentRowMinusScore) === 0){
          this.$message.error('所扣减金额不能为0')
          return
        }
        let dic = {userId:this.currentChoseOrder.userId,score:this.currentRowMinusScore,type:2,refer:'order',orderId:this.currentChoseOrder.id}
        this.$http.post(ORDERING_POST_USERS_SCORE_CHANGE,dic).then(res=>{
          if (res.code === 200){
            this.$message.success('操作成功')
            this.getData()
            getUserInfo();
          }
          this.cancelMinusClick()
        })
      },
      minusUserScoreClick(row){
        this.currentChoseOrder = row
        this.showMinusScoreDialogFlag  =true
      },
      deleteClick(row){
        this.$confirm('确认删除该条菜品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.post(ORDERING_POST_USER_ORDER_DELETE,{id:row.id}).then(res=>{
            if(res.code === 200){
              this.$message.success('操作成功');
              setTimeout(()=>{
                this.resetClick()
              },600);
              getUserInfo();
            }
            this.showGearsFlag = false
          })
        }).catch(()=>{})
      },

    }
}
</script>

<style scoped lang="scss">
.bg{
  background-color: white;
  padding: 20px;
}
.top-bg{
  background-color: #f9f9f9;
  border: 1px solid #ebeef5;
  min-height: 60px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  padding: 18px 0 0;
  display: flex;
  align-items: center;
  .item{
    display: flex;
    align-items: center;
    margin-right: 10px;
    margin-bottom: 18px;
    flex-shrink: 0;

  }
  .first{
    min-width: 100px;
    text-align: right;
  }
}
</style>